package com.vcredit.creditcat.service.product.xyh;

import io.netty.util.internal.StringUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.creditcat.enumtype.AuthItemEnum;
import com.vcredit.creditcat.enumtype.auth.SupplementItemEnum;
import com.vcredit.creditcat.enumtype.product.xyh.RelationEnum;
import com.vcredit.creditcat.model.AddressList;
import com.vcredit.creditcat.model.AuthPersonalAddress;
import com.vcredit.creditcat.model.Cust;
import com.vcredit.creditcat.model.CustProductApply;
import com.vcredit.creditcat.model.CustSupplementItem;
import com.vcredit.creditcat.model.Relative;
import com.vcredit.creditcat.model.base.AbstractItem;
import com.vcredit.creditcat.service.product.IProductApplyNewService;
import com.vcredit.creditcat.service.product.shared.ProductApplyServiceAdaptor;
import com.vcredit.creditcat.util.ConcurrentDateUtil;
import com.vcredit.creditcat.util.IdcardUtils;
import com.vcredit.creditcat.util.JsonUtil;
import com.vcredit.creditcat.util.Utility;
import com.vcredit.creditcat.vo.ProductApplyResultVo;
import com.vcredit.creditcat.vo.auth.AuthAlipayExt;
import com.vcredit.creditcat.vo.auth.AuthIdentityExt;
import com.vcredit.creditcat.vo.auth.AuthMobileExt;
import com.vcredit.creditcat.vo.auth.AuthPersonalInfoExt;
import com.vcredit.creditcat.vo.auth.AuthSecreditExt;
import com.vcredit.creditcat.vo.auth.RelativeListExt;
import com.vcredit.creditcat.vo.product.xyh.AddressBookVo;
import com.vcredit.creditcat.vo.product.xyh.CompanyDto;
import com.vcredit.creditcat.vo.product.xyh.CreditMobile;
import com.vcredit.creditcat.vo.product.xyh.CreditZmxy;
import com.vcredit.creditcat.vo.product.xyh.QueryParamVo;
import com.vcredit.creditcat.vo.product.xyh.QueryResultVo;
import com.vcredit.creditcat.vo.product.xyh.RelationVo;
import com.vcredit.creditcat.vo.product.xyh.ResultVo;
import com.vcredit.creditcat.vo.product.xyh.UserCreditInfoVo;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.HttpRequest;
import com.vcredit.framework.util.JacksonUtil;

/**
 * 信用花申请实现类
 * @author zhaoqi01
 *
 */
@Service(ProductApplyServiceAdaptor.BEANNAME_PREFIX + 6)
public class XYHApplyServiceImpl implements IProductApplyNewService{
	
	private  Logger logger = LoggerFactory.getLogger(XYHApplyServiceImpl.class);
	
	private static final Integer TIMEOUT = 60; // 请求超时时间60s
	
	@Value("${product.xyh.queryUrl}")
	private String queryUrl;
	
	@Value("${product.xyh.creditUrl}")
	private String creditUrl;
	
	@Value("${resource.image.url}")
	private String imagUrl;

	@Log
	@Override
	public ProductApplyResultVo apply(Map<Integer, AbstractItem> custAuthInfoMap, 
			Map<Long, CustSupplementItem> custSupplementItemMap, Map<String,Object> otherParams) {
		try {
			/**
			 * 1、取出认证项数据
			 **/
			Cust cust = (Cust) otherParams.get("cust");
			CustSupplementItem supplement;
			if(custSupplementItemMap.get(SupplementItemEnum.XYH_BASE_INFO.getItemId())!=null){
				supplement = custSupplementItemMap.get(SupplementItemEnum.XYH_BASE_INFO.getItemId());
			}else{
				supplement = custSupplementItemMap.get(SupplementItemEnum.Common_BASE_INFO.getItemId());
			}
			AuthPersonalInfoExt personalInfo = JacksonUtil.Json2Obj(supplement.getDataEntity(), new TypeReference<AuthPersonalInfoExt>(){});	
			AuthIdentityExt identity = (AuthIdentityExt)custAuthInfoMap.get(AuthItemEnum.VERIFY_FACE_PAIR.getCode());
			AuthMobileExt authMobile = (AuthMobileExt)custAuthInfoMap.get(AuthItemEnum.MOBILE.getCode());
			AuthAlipayExt alipay = (AuthAlipayExt)custAuthInfoMap.get(AuthItemEnum.ALIPAY.getCode());
			RelativeListExt relativeListVo = (RelativeListExt)custAuthInfoMap.get(AuthItemEnum.CONTACTS.getCode());
			AuthSecreditExt secredit = (AuthSecreditExt)custAuthInfoMap.get(AuthItemEnum.SESAME_CREDIT.getCode());
			
			/**
			 * 2、处理撞库和授信状态
			 **/
			QueryParamVo queryParam = new QueryParamVo(identity.getCitizenId(), identity.getName(),authMobile.getMobile());
			String queryParamStr = JacksonUtil.Obj2Json(queryParam);
			logger.info("信用花查询状态入参："+queryParamStr);
			String queryResultStr = HttpRequest.doJson(queryUrl, queryParamStr, TIMEOUT);
			logger.info("信用花查询状态出参："+queryResultStr);
			ResultVo<QueryResultVo> result = JacksonUtil.Json2Obj(queryResultStr, new TypeReference<ResultVo<QueryResultVo>>(){});
			CustProductApply custProductApply = new CustProductApply();
			if(!result.getStatus().equals("000")) {
				custProductApply.setAuditResult(0);
				custProductApply.setRejectMsg(result.getMessage());
				custProductApply.setIsApply(true);
				custProductApply.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(),30)));
				return new ProductApplyResultVo(custProductApply);
			}
			
			if(result.getData()!=null){							
				QueryResultVo content = result.getData();
				// 处理黑名单、灰名单
				if("1".equals(content.getListType())) {
					custProductApply.setAuditResult(0);
					custProductApply.setRejectMsg("信用花黑名单");
					custProductApply.setIsApply(false);
					return new ProductApplyResultVo(custProductApply);
				} else if("2".equals(content.getListType())) {
					custProductApply.setAuditResult(0);
					custProductApply.setRejectMsg("信用花灰名单");
					custProductApply.setIsApply(true);
					custProductApply.setCreditApplyTime(content.getListExpireDate() == null ? null : ConcurrentDateUtil.formatDateTime(content.getListExpireDate()));
					return new ProductApplyResultVo(custProductApply);
				}
				if(!StringUtil.isNullOrEmpty(content.getCustIdno())  
						&& identity.getCitizenId().equals(content.getCustIdno())) {
					// 撞库				
					if(!("502".equalsIgnoreCase(content.getChannel()) 
							||"503".equalsIgnoreCase(content.getChannel())))
					{
						custProductApply.setAuditResult(0);
						custProductApply.setRejectMsg("用户已在信用花注册");
						custProductApply.setIsApply(false);
						return new ProductApplyResultVo(custProductApply);
					}														
									
					// 处理授信状态
					String creditStatus = content.getCreditStatus();
					if(creditStatus==null){
						return new ProductApplyResultVo("信用花状态查询异常！");
					}
					switch (creditStatus) {
					case "2": // 拒绝授信
						custProductApply.setAuditResult(0);
						custProductApply.setRejectMsg("信用花拒绝授信");
						custProductApply.setIsApply(true);
						custProductApply.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(),30)));
						return new ProductApplyResultVo(custProductApply);
					case "4": // 已完成授信
						custProductApply.setAuditResult(1);
						custProductApply.setIsApply(false);
						custProductApply.setCreditAmt(content.getTotalAccount() == null ? 0 : (int)content.getTotalAccount().doubleValue());
						custProductApply.setCreditExpiretime(content.getAccountExpireDate() == null ? null : ConcurrentDateUtil.formatDateTime(content.getAccountExpireDate()));
						custProductApply.setServiceRate(content.getMonthPlatServiceRate() == null ? null : new BigDecimal(content.getMonthPlatServiceRate()));
						custProductApply.setTotalServiceRate(content.getMonthComprehRate() == null ? null : new BigDecimal(content.getMonthComprehRate()));
						return new ProductApplyResultVo(custProductApply);
					case "5": // 授信中
						custProductApply.setAuditResult(2);
						custProductApply.setRejectMsg("信用花授信中");
						custProductApply.setIsApply(false);
						return new ProductApplyResultVo(custProductApply);
						
					case "7": // 信用补救，可重新授信
						custProductApply.setAuditResult(7);
						custProductApply.setRejectMsg("信用花信用补救");
						custProductApply.setIsApply(false);
						return new ProductApplyResultVo(custProductApply);
					default: //
						custProductApply.setAuditResult(0);
						custProductApply.setRejectMsg("信用花授信状态不明！");
						custProductApply.setIsApply(false);
						return new ProductApplyResultVo(custProductApply);
					}
				}
			}
			/** 
			 * 3、提交用户信息 
			 */
			int age = IdcardUtils.getAge(cust.getCustIdno());
			if(age<20 || age>40){//年龄必须在20-40之间
				custProductApply.setAuditResult(0);
				custProductApply.setRejectMsg("年龄必须在20-40之间！");
				custProductApply.setIsApply(false);
				return new ProductApplyResultVo(custProductApply);
			}
			UserCreditInfoVo creditInfo = new UserCreditInfoVo();
			CompanyDto company = new CompanyDto();
			//高级实名
			if(identity.getLiveCompareValue()==null || identity.getLiveCompareValue()< 75){
				custProductApply.setAuditResult(0);
				custProductApply.setRejectMsg("活体分值必须大于75！");
				custProductApply.setIsApply(true);
				custProductApply.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(),30)));
				return new ProductApplyResultVo(custProductApply);
			}
			creditInfo.setCustIdno(cust.getCustIdno());
			creditInfo.setCustName(cust.getCustName());
			creditInfo.setChannel("502");
			creditInfo.setOcrIdno(identity.getCitizenId());
			creditInfo.setOcrName(identity.getName());
			creditInfo.setOcrAddress(identity.getAddress());
			creditInfo.setIdFrontCode(imagUrl + "/" + identity.getIdFront());
			creditInfo.setFacepairCode(imagUrl + "/" + identity.getIdFace());
			creditInfo.setLiveCompareValue(identity.getLiveCompareValue().toString());
			//基本信息
			for(AuthPersonalAddress address:personalInfo.getPersonalAddrList()){
				if(address.getAddressType()==0){//公司地址
					company.setWorkCity(address.getCity()); 
				}else if(address.getAddressType()==2){//居住地址
					company.setCurrentLocAdd(address.getProvince()+address.getCity()+address.getZone()+address.getAddress());
					//信用花常用地址与详细地址一致
					company.setCompanyAdd(address.getProvince()+address.getCity()+address.getZone()+address.getAddress());
				}
				if(address.getGeoLatitude()!=null && address.getGeoLongitude()!=null){
					company.setCurrentLocLatitude(address.getGeoLatitude());
					company.setCurrentLocLongitude(address.getGeoLongitude());
				}
			}		
			creditInfo.setMarriage(personalInfo.getMarriageKey());		
			creditInfo.setEducation(personalInfo.getEducationKey());
			
			
			int professionKey = 99; //职业默认其他
			if(personalInfo.getProfessionKey()<=9){
				professionKey = personalInfo.getProfessionKey();
			}
			company.setProfessionType(professionKey);
			int salaryKey = 1; //月收入 没有值默认1000以下
			if(personalInfo.getSalaryKey()<5){
				salaryKey = personalInfo.getSalaryKey();
			}else if(personalInfo.getSalaryKey()==5 || personalInfo.getSalaryKey()==6 ){
				salaryKey = 5;
			}else if(personalInfo.getSalaryKey()>6){
				salaryKey = 6;
			}
			company.setMonthlyIncome(salaryKey);	
			company.setCommonEmail(personalInfo.getEmail());
			creditInfo.setCompanyDto(company);
			//手机认证
			CreditMobile mobile =  new CreditMobile();
			mobile.setMobile(authMobile.getMobile());
			mobile.setMobileId(authMobile.getMobileId());
			mobile.setRegisterIdno(authMobile.getRegisterIdNo());
			mobile.setRegisterName(authMobile.getRegisterName());
			mobile.setWebsite(authMobile.getWebsite());
			creditInfo.setCreditMobile(mobile);
			//芝麻信用
			CreditZmxy zmxy = new CreditZmxy();
			zmxy.setZmxyScore(secredit.getZmxyScore());
			creditInfo.setCreditZmxy(zmxy);
			//紧急联系人
			if (Utility.isNullOrEmpty(relativeListVo.getRelativeList()) || Utility
					.isNullOrEmpty(relativeListVo.getAddressList())) {
				logger.error("紧急联系人不能为空:"+ JsonUtil.obj2Json(relativeListVo,false));
				custProductApply.setAuditResult(0);
				custProductApply.setRejectMsg("紧急联系人不能为空！");
				custProductApply.setIsApply(true);
				custProductApply.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(),30)));
				return new ProductApplyResultVo(custProductApply);
			}
			if (relativeListVo.getAddressList().size() <= 30) {
				custProductApply.setAuditResult(0);
				custProductApply.setRejectMsg("通讯录联系人个数不能少于30个！");
				custProductApply.setIsApply(true);
				custProductApply.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(),30)));
				return new ProductApplyResultVo(custProductApply);
			}
			List<RelationVo> relationList = new ArrayList<RelationVo>();
			for(Relative relative: relativeListVo.getRelativeList()){
				RelationVo relation =  new RelationVo();
				relation.setMobileNo(relative.getRelationMobile());
				relation.setName(relative.getRelationName());
				relation.setRelation(relative.getRelationType());
				if(relative.getRelation()<=4){ //信用猫1,2,3,4均是亲戚关系
					relation.setPriority(RelationEnum.FAMILY.getCode());
				}else if(relative.getRelation()==5){
					relation.setPriority(RelationEnum.COLLEAGUE.getCode());
				}else if(relative.getRelation()==6){
					relation.setPriority(RelationEnum.FRIEND.getCode());
				}else{
					relation.setPriority(RelationEnum.OTHERS.getCode());
				}				
				relationList.add(relation);
			}
			creditInfo.setRelativeList(relationList);
			
			List<AddressBookVo> addressBookList = new ArrayList<AddressBookVo>();
			for(AddressList address : relativeListVo.getAddressList()){
				AddressBookVo addressBookVo = new AddressBookVo();
				addressBookVo.setMobileNo(address.getMobile());
				addressBookVo.setName(address.getName());
				addressBookVo.setPriority(0);
				addressBookVo.setRelation(0);
				addressBookList.add(addressBookVo);
			}
			creditInfo.setAddressList(addressBookList);
			String submitParam = JacksonUtil.Obj2Json(creditInfo);
			String submitResultStr = HttpRequest.doJson(creditUrl,submitParam , TIMEOUT);
			ResultVo<Object> submitresult = JacksonUtil.Json2Obj(submitResultStr, new TypeReference<ResultVo<Object>>(){});
			if(submitresult.getStatus().equals("000")){
				custProductApply.setAuditResult(2);
				custProductApply.setRejectMsg("信用花授信中");
				custProductApply.setIsApply(false);
				custProductApply.setCreditApplyTime("");
				return new ProductApplyResultVo(custProductApply);
			}else{
				custProductApply.setAuditResult(0);
				custProductApply.setRejectMsg("信用花提交失败："+submitresult.getMessage());
				custProductApply.setIsApply(true);
				custProductApply.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(),30)));
				return new ProductApplyResultVo(custProductApply);
			}
			
		} catch (Exception e) {
			logger.error("信用花申请异常", e);
			return new ProductApplyResultVo("信用花申请异常！");
		}
		
		
	}
	
	

}
